package com.fansl.allround.common.security.component;

import com.fansl.allround.common.core.constant.SecurityConstants;
import com.fansl.allround.common.core.constant.enums.ServiceTypeEnum;
import com.fansl.allround.common.security.service.AllroundSysUser;
import com.fansl.allround.common.security.service.AllroundUcenterUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.oauth2.provider.token.UserAuthenticationConverter;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author fansl
 * @Description: 根据checktoken 的结果转化用户信息
 * @date 2019/7/12 14:14
 */
@Slf4j
public class AllroundUserAuthenticationConverter implements UserAuthenticationConverter {
    private static final String N_A = "N/A";

    @Override
    public Map<String, ?> convertUserAuthentication(Authentication authentication) {
        Map<String, Object> response = new LinkedHashMap<>();
        response.put(USERNAME, authentication.getName());
        if (authentication.getAuthorities() != null && !authentication.getAuthorities().isEmpty()) {
            response.put(AUTHORITIES, AuthorityUtils.authorityListToSet(authentication.getAuthorities()));
        }
        return response;
    }

    /**
     * @param map check-token 返回的全部信息
     * @return
     */
    @Override
    public Authentication extractAuthentication(Map<String, ?> map) {
        if (map.containsKey(USERNAME)) {
            if (map.containsKey(SecurityConstants.DETAILS_SERVICE_NAME)) {
                if (ServiceTypeEnum.BACKEND.name()
                        .equals(map.get(SecurityConstants.DETAILS_SERVICE_NAME))) {
                    Collection<? extends GrantedAuthority> authorities = getAuthorities(map);
                    String username = (String) map.get(SecurityConstants.DETAILS_USERNAME);
                    Integer id = (Integer) map.get(SecurityConstants.DETAILS_USER_ID);
                    Integer deptId = (Integer) map.get(SecurityConstants.DETAILS_DEPT_ID);
                    AllroundSysUser user = new AllroundSysUser(id, deptId, username, N_A, true,
                            true, true, true, authorities);
                    return new UsernamePasswordAuthenticationToken(user, N_A, authorities);
                }
                if (ServiceTypeEnum.UCENTER.name()
                        .equals(map.get(SecurityConstants.DETAILS_SERVICE_NAME))) {
                    Collection<? extends GrantedAuthority> authorities = Collections.EMPTY_SET;
                    String username = (String) map.get(SecurityConstants.DETAILS_USERNAME);
                    Integer id = (Integer) map.get(SecurityConstants.DETAILS_USER_ID);
                    AllroundUcenterUser user = new AllroundUcenterUser(id, username, N_A, authorities, true);
                    return new UsernamePasswordAuthenticationToken(user, N_A, authorities);
                }
            }
        }
        return null;
    }

    private Collection<? extends GrantedAuthority> getAuthorities(Map<String, ?> map) {
        Object authorities = map.get(AUTHORITIES);
        if (authorities instanceof String) {
            return AuthorityUtils.commaSeparatedStringToAuthorityList((String) authorities);
        }
        if (authorities instanceof Collection) {
            return AuthorityUtils
                    .commaSeparatedStringToAuthorityList(StringUtils
                            .collectionToCommaDelimitedString((Collection<?>) authorities));
        }
        throw new IllegalArgumentException("Authorities must be either a String or a Collection");
    }
}
